﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
namespace Talentnet.Core.Utilities
{
    public static class EntityConverter
    {
        public static T GetEntity<T>(this DataRow row)
        {
            Type t = typeof(T);
            //Create the object
            T retVal = (T)Activator.CreateInstance(t);
            PropertyInfo[] pis = t.GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                //prop.PropertyType
                if (row.Table.Columns[pi.Name] != null && pi.CanWrite)
                {
                    if (pi.PropertyType.IsInstanceOfType(row[pi.Name])) pi.SetValue(retVal, row[pi.Name], null);
                }
            }

            return retVal;
        }
        public static T GetEntity<T>(this IDataReader reader)
        {
            Type t = typeof(T);
            //Create the object
            T retVal = (T)Activator.CreateInstance(t);
            PropertyInfo[] pis = t.GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                //prop.PropertyType
                if (reader[pi.Name] != DBNull.Value && pi.CanWrite)
                {
                    if (pi.PropertyType.IsInstanceOfType(reader[pi.Name])) pi.SetValue(retVal, reader[pi.Name], null);
                }
            }

            return retVal;
        }
        public static List<T> GetEntities<T>(this DataTable dataList)
        {

            List<T> retVal = new List<T>();
            foreach (DataRow row in dataList.Rows)
            {
                retVal.Add(GetEntity<T>(row));
            }
            return retVal;
        }
    }
}
